﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Sop;

namespace EFCachingProvider.ScalableCache
{
    public partial class ScalableCache
    {
        // Entity Set Manager helper.
        private class EntitySetManager
        {
            private readonly Sop.Collections.Generic.ISortedDictionary<string, Sop.Collections.Generic.ISortedDictionary<string, bool>>
                _entitySets = new Sop.Collections.Generic.SortedDictionary<string, Sop.Collections.Generic.ISortedDictionary<string, bool>>();

            public void SetItem(string key, CacheEntry entry, bool createOrRemove)
            {
                if (entry.DependentEntitySets != null)
                {
                    foreach (var entitySet in entry.DependentEntitySets)
                    {
                        SetItem(entitySet, key, createOrRemove);
                    }
                }
            }
            public void SetItem(string entitySetName, string itemKey, bool createOrRemove)
            {
                Sop.Collections.Generic.ISortedDictionary<string, bool> entitySet;
                if (!_entitySets.TryGetValue(entitySetName, out entitySet))
                {
                    entitySet = new Sop.Collections.Generic.SortedDictionary<string, bool>();
                    _entitySets.Add(entitySetName, entitySet);
                }
                entitySet.Add(itemKey, createOrRemove);
            }
            public void ProcessItems(ScalableCache scalableCache)
            {
                foreach (var entitySet in _entitySets)
                {
                    var dependentEntityStore = scalableCache.GetEntitySetStore(entitySet.Key, true);
                    dependentEntityStore.Locker.Lock();
                    foreach (var kvp in entitySet.Value)
                    {
                        if (kvp.Value)
                            dependentEntityStore[kvp.Key] = null;
                        else
                            dependentEntityStore.Remove(kvp.Key);
                    }
                    if (dependentEntityStore.Count == 0)
                    {
                        IStoreFactory storeFactory = new StoreFactory();
                        // remove the empty dependent entity set.
                        storeFactory.Remove(scalableCache.Server.SystemFile.Store, entitySet.Key);
                        dependentEntityStore.Dispose();
                    }
                    dependentEntityStore.Locker.Unlock();
                }
            }
        }
    }
}
